<?php


namespace App\Services;



use App\Models\Audio;
use App\Models\Category;
use App\Models\Font;
use App\Models\Information;
use App\Models\Map;
use App\Models\Photo;
use App\Models\Product;
use App\Models\Team;
use App\Models\Video;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;

class Compose
{

    protected $information;

    protected $picture;

    protected $videos;

    protected $audios;

    protected $category;

    protected $team;

    protected $photo;

    protected $name_maps;

    protected $three_maps;

    protected $products;

    protected $font;

    public function __construct()
    {


        $this->information = Information::where('status',1)->get()->shuffle();

        $this->videos = Video::where('status',1)->get()->shuffle();

        $this->audios = Audio::where('status',1)->get()->shuffle();

        $this->category = Category::with('sub')->where('pid',0)->get();


        $this->photo = Photo::where('status',1)->get()->shuffle();


        $this->name_maps = Map::where('status',1)->where('type',0)->get()->shuffle();

        $this->three_maps = Map::where('status',1)->where('type',1)->get()->shuffle();

        $this->products = Product::where('source',1)->get();

        $this->font = Font::where('status',1)->get()->shuffle();

    }


    public function start(){
        app(ConfigService::class)->cache();
        $count = 0;
        $image = new ComposeImage();
        $position = [1=>'top-left',2=>'top-right',3=>'middle-left',4=>'middle-right',5=>'bottom-left',6=>'bottom-right'];
        $three_separator = [' ','-','/','.'];
        foreach($this->information as $information){


            $audio = $this->audios->pop();
            $photo = $this->photo->pop();

            if(!$photo){
                break;
            }

            if(!$photo->video){
                $video = $this->videos->pop();
            }



            $name_maps = $this->name_maps->pop();
            $this->name_maps->prepend($name_maps);

            $three_maps = $this->three_maps->pop();
            $this->three_maps->prepend($three_maps);


            $font = $this->font->pop();
            $this->font->prepend($font);



            if(rand(0,1)){
                $rotate_1 = rand(0,30);
            }else{
                $rotate_1 = -rand(0,30);
            }

            if(rand(0,1)){
                $rotate_2 = rand(0,30);
            }else{
                $rotate_2 = -rand(0,30);
            }





            $name_position = array_get($position,$photo->name_maps_position,'top-left');
            $three_position = array_get($position,$photo->three_maps_position,'bottom-right');

            //$img = 'photo/'.md5(Str::uuid()).'.jpg';
            /*$compose_img = $image;
            if($name_maps){
                $compose_img = $image->addMaps(public_path('uploads/'.$name_maps->img),$rotate_1,$name_position);
            }

            if($three_maps){
                $compose_img = $compose_img->addMaps(public_path('uploads/'.$three_maps->img),$rotate_2,$three_position);
            }
            $compose_img->generate(public_path('uploads/'.$photo->img),public_path('uploads/'.$img));*/

            $img = $photo->img;



            $three_separator_random_index = array_rand($three_separator);
            $product_insert = [
                'team_id'=>$information->team_id,
                'font_id'=>$font->id,
                'name'=>$information->nickname,
                'img'=>$img,
                'height'=>$information->height,
                'weight'=>$information->weight,
                'cup'=>$information->cup,
                'photo'=>$photo->img,
                'atlas'=>$photo->atlas,
                'name_map_rotate'=>$rotate_1,
                'name_map_position'=>$name_position,
                'name_class'=>$this->getNameClass(),
                'three_map_rotate'=>$rotate_2,
                'three_map_position'=>$three_position,
                'three_separator'=>array_get($three_separator,$three_separator_random_index),
                'three_class'=>$this->getThreeClass(),
                'video'=>isset($video)?$video->video:"",
                'video_cover'=>isset($video)?$video->cover:"",
                'video_authentication'=>0,
                'show_video'=>0,
                'audio'=>isset($audio)?$audio->audio:"",
                'audio_duration'=>isset($audio)?$audio->duration:"",
                'source'=>1,
                'status'=>1,
                'hairstyle'=>$photo->hairstyle,
                'scheduling'=>$information->scheduling,
                'is_secretly'=>$information->is_secretly,
                'is_specific_service'=>$information->is_specific_service,
                'gift_specific_service'=>$information->gift_specific_service,
                'custom_service'=>$information->custom_service,
                'gift_not_specific_service'=>$information->gift_not_specific_service,
                'custom_service2'=>$information->custom_service2,
                'prohibited_guests'=>$information->prohibited_guests,
                'price'=>$information->price,
            ];



            if($photo->video){
                $product_insert['video'] = $photo->video;
                $product_insert['video_cover'] = $photo->img;
                $product_insert['video_authentication'] = 1;
            }


            //获取描述词
            $labels = [];
            $height_label = $this->getHeightLabel($information->height);
            if($height_label){
                $labels[] = $height_label;
            }

            $cup_label = $this->getCupLabel($information->cup);
            if($cup_label){
                $labels[] = $cup_label;
            }


            if($information->is_secretly == 1){
                $secret_label = $this->getSecretlyLabel();
                if($secret_label){
                    $labels[] = $secret_label;
                }
            }

            if($information->is_specific_service == 1){
                $labels[] = $this->getSpecificServiceLabel($information->is_specific_service,$information->gift_specific_service);
            }elseif ($information->is_specific_service == 2){
                $labels[] = $this->getSpecificServiceLabel($information->is_specific_service,$information->gift_not_specific_service);
            }


            if ($information->prohibited_guests){
                $labels[] = $this->getProhibitedGuestsLabel($information->prohibited_guests);
            }


            $product_insert['labels'] = $labels;




            if($name_maps){
                $product_insert['name_map'] = $name_maps->img;
            }

            if($three_maps){
                $product_insert['three_map'] = $three_maps->img;
            }

            if($this->products->isEmpty()){

                $product = Product::create($product_insert);
                app(ImageService::class)->resize_product($product);
            }else{
                $product = $this->products->shift();

                Product::where('id',$product->id)->update($product_insert);

                /*if($product->img && file_exists(public_path('uploads/'.$product->img))){
                    @unlink(public_path('uploads/'.$product->img));

                    $size_file = str_replace('.','-50.',$product->img);
                    @unlink(public_path('uploads/'.$size_file));
                }*/
                app(ImageService::class)->resize_product(Product::find($product->id));
            }


            $count++;
        }

        if($this->products->isEmpty()){
            $delete_ids = $this->products->pluck('id');
            Product::whereIn('id',$delete_ids)->where('source',1)->delete();
        }
        $this->resizeFont();

        $this->retool();

        //清理缓存
        foreach(config('global.cache')  as $key){
            Cache::forget($key);
        }

        ConfigService::cache();


        return $count;
    }

    /**
     * 对字体包做好压缩处理前的准备
     *
     * @return void
     */
    public function resizeFont(){
        $font = Font::with('products')->where('status',1)->get();
        $view = view('admin.resize-font',compact('font'));
        file_put_contents(public_path('uploads/font/res.html'),$view->render());
        file_put_contents(public_path('uploads/font/font.signal'),1);//传递字体更新信号，shell脚本获取信号，压缩字体
    }


    /**
     * 获取身高描述词
     *
     * @param $height
     * @return array|\ArrayAccess|mixed|string
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function getHeightLabel($height){
        if ($height <= 155){
            $tags = app('cache.config')->get('height1_tags');
        }elseif ($height>=156 && $height<=165){
            $tags = app('cache.config')->get('height2_tags');
        }else{
            $tags = app('cache.config')->get('height3_tags');
        }

        if($tags){
            $tags = explode('|',$tags);
            return array_get($tags,array_rand($tags));
        }

        return "";
    }

    /**
     * 获取罩杯描述词
     *
     * @param $cup
     * @return array|\ArrayAccess|mixed|string
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function getCupLabel($cup){
        if ($cup == 'B'){
            $tags = app('cache.config')->get('b_tags');
        }elseif ($cup == 'C'){
            $tags = app('cache.config')->get('c_tags');
        }elseif($cup == 'D'){
            $tags = app('cache.config')->get('d_tags');
        }elseif($cup == 'E'){
            $tags = app('cache.config')->get('e_tags');
        }elseif($cup == 'F'){
            $tags = app('cache.config')->get('f_tags');
        }elseif($cup == 'G'){
            $tags = app('cache.config')->get('g_tags');
        }elseif($cup == 'H'){
            $tags = app('cache.config')->get('h_tags');
        }else{
            return "";
        }
        if($tags){
            $tags = explode('|',$tags);
            return array_get($tags,array_rand($tags));
        }

        return "";

    }

    /**
     * 获取暗配描述词
     *
     * @return array|\ArrayAccess|mixed|string
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function getSecretlyLabel(){
        $tags = app('cache.config')->get('secretly_tags');
        if($tags){
            $tags = explode('|',$tags);
            return array_get($tags,array_rand($tags));
        }
        return "";
    }

    /**
     * 获取送禮描述词
     * @param $type
     * @param $server
     * @return string
     */
    public function getSpecificServiceLabel($type,$server){

        if($type == 1){

            $des = [];
            foreach ($server as $item){
                $des[] = array_get(Product::SPECIFIC_SERVICE,$item);
            }
            return '預約送'.implode('',$des);


        }elseif($type == 2){
            return array_get(Product::SPECIFIC_NOT_SERVICE,$server);
        }
        return "";
    }

    /**
     * 获取禁客描述词
     * @param $guests
     * @return string
     */
    public function getProhibitedGuestsLabel($guests){

        if($guests){
            $tag = '禁';
            $des = [];
            foreach ($guests as $item){
                $des[] = array_get(Product::PROHIBITED_GUESTS,$item);
            }
            $tag .= implode(' ',$des);
            return $tag;

        }
        return "";
    }

    /**
     * 获取姓名class
     *
     * @return array|\ArrayAccess|mixed|null
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function getNameClass(){
        $name_class = app('cache.config')->get('name_class');
        if($name_class){
            $name_class = explode(',',$name_class);
            $name_class = array_filter($name_class);
            return array_get($name_class,array_rand($name_class));
        }
        return null;
    }

    /**
     * 获取三维class
     *
     * @return array|\ArrayAccess|mixed|null
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function getThreeClass(){
        $three_class = app('cache.config')->get('three_class');
        if($three_class){
            $three_class = explode(',',$three_class);
            $three_class = array_filter($three_class);
            return array_get($three_class,array_rand($three_class));
        }
        return null;
    }


    /**
     * 使每一页10条数据有一个播放视频的
     *
     * @return void
     */
    public function retool(){

        $teams = Team::get();
        foreach($teams as $item){
            $count = Product::where('team_id',$item->id)->count();
            $page = ceil($count/10);
            Product::where('team_id',$item->id)->where('video_authentication',1)->take($page)->update([
                'show_video'=>1,
            ]);

        }
    }
}
